﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Waker.BAL;
using DevExpress.XtraNavBar;
using DevExpress.XtraTabbedMdi;
using Waker.Base;
using Waker.Common;
using DevExpress.XtraBars;
using System.Diagnostics;
using DevExpress.XtraBars.Docking;
using Waker.Entitys;
using Waker.APIs.ZKT;
using Waker.APIs.IDCards;
using Waker.APIs.ADS;
using Waker.APIs.Cards;
using System.Threading;
using Waker.APIs.NVR;
using System.Runtime.InteropServices;
using System.IO;
using System.Reflection;
using DevExpress.XtraReports.UI;
using System.Configuration;
using System.Threading.Tasks;

namespace Waker
{
    public partial class FormMain : Base.FormBase
    {
        #region 字段
        HCNetSDK.NET_DVR_JPEGPARA _NVR_JpgPara = new HCNetSDK.NET_DVR_JPEGPARA() { wPicQuality = 0, wPicSize = 0 };
        NET_DVR_DEVICEINFO_V30 _NVR_DeviceInfo = new NET_DVR_DEVICEINFO_V30();
        #endregion

        public FormMain()
        {
            try
            {
                InitializeComponent();


                Splash.Status = "状态:初始化基础数据";
                BindSkins();
                InitData();
                InitNVR();
                System.Threading.Thread.Sleep(100);

                //Splash.Status = "状态:初始化室内LED";
                //InitLEDInDoor();
                //System.Threading.Thread.Sleep(100);

                Splash.Status = "状态:初始化身份证阅读器";
                InitIDCard();
                System.Threading.Thread.Sleep(100);

                Splash.Status = "状态:初始化指纹设备";
                InitZKTFinger();
                System.Threading.Thread.Sleep(100);

                Splash.Status = "状态:初始化读卡器设备";
                System.Threading.Thread.Sleep(100);

                Splash.Status = "状态:初始化门禁设备";
                InitADS();
                System.Threading.Thread.Sleep(100);

                Splash.Status = "状态:初始化视频设备";
                System.Threading.Thread.Sleep(100);




                Splash.Close();
                var login = new FormLogin();
                if (login.ShowDialog() != DialogResult.OK)
                {
                    ExitSystem(false);
                }
                InitLEDInDoor();
                this.Text = Consts.System_Name;
                this.barTxtAuthor.Caption = Consts.AuthorName;
                this.barTxtCurrUser.Caption = Session._CurrUserName;
            }
            catch (Exception ex)
            {
                UI.ShowError(ex.Message);
            }
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            BindMenu();
            timerCurrTime.Enabled = true;
            timerDeviceSyncData.Enabled = true;
            timerDeviceEvent.Enabled = true;

            this.gridControl1.DataSource = Session.ListADSEventDataToDisplay;
        }

        #region 菜单
        private void BindMenu()
        {
            NavBarItem firstItem = null;
            navBarControl1.Groups.Clear();
            navBarControl1.Items.Clear();

            DataTable dt = new BAL_SystemSetting().GetMenuByUserCode(Session._CurrUserCode);
            if (dt == null || dt.Rows.Count < 1)
                return;
            var listDt = dt.AsEnumerable();
            NavBarItem nbiFirst = null;
            listDt.Where(f =>
                f["ParentCode"] == DBNull.Value
                || string.IsNullOrEmpty(f["ParentCode"].ToString())
                )
                .OrderBy(f => f["FunSort"])
                .ToList().ForEach(dr =>
             {
                 //检查权限
                 //if (!UserInfo.Privilege.Contains(dr["FunCode"].ToString()))
                 //    continue; 
                 var groupname = dr["FunName"].ToString();

                 NavBarGroup nbg = new NavBarGroup(groupname);
                 nbg.Hint = groupname;
                 //nbg.SmallImageIndex = dr["ImageIndex"] == DBNull.Value ? 0 : Convert.ToInt32(dr["ImageIndex"]);

                 //nbg.LargeImage = Util.GetIconResource(IcoSourcePath + dr["Image"].ToString(), 32, 32);
                 if (dr["Image"] != DBNull.Value)
                     nbg.SmallImage = Util.GetIconResource(Consts.MenuIcoPath + dr["Image"].ToString(), 32, 32);
                 //DataTable dt = Util.GetNewDataTable(dtAll, "ParentCode='" + dr["FunCode"].ToString() + "' and Type=1");

                 listDt.Where(f =>
                     f["ParentCode"] != DBNull.Value
                     && !string.IsNullOrEmpty(f["ParentCode"].ToString())
                     && f["ParentCode"].ToString() == dr["FunCode"].ToString()
                     )
                      .OrderBy(f => f["FunSort"])
                     .ToList().ForEach(drItem =>
                 {

                     //检查权限
                     //if (!UserInfo.Privilege.Contains(drr["FunCode"].ToString()))
                     //    continue;
                     NavBarItem nbi = navBarControl1.Items.Add();
                     if (nbiFirst == null)
                         nbiFirst = nbi;
                     var funname = drItem["FunName"].ToString();

                     nbi.Caption = funname;
                     nbi.Hint = funname;
                     nbi.Tag = drItem["FunCode"].ToString();
                     nbi.LinkClicked += new NavBarLinkEventHandler(nbg_LinkClicked);
                     //nbi.SmallImage = Util.GetIconResource(IcoSourcePath + drr["Image"].ToString(), 16, 16);
                     //nbi.SmallImageIndex = drItem["ImageIndex"] == DBNull.Value ? 0 : Convert.ToInt32(drItem["ImageIndex"]);
                     if (drItem["Image"] != DBNull.Value)
                         nbi.SmallImage = Util.GetIconResource(Consts.MenuIcoPath + drItem["Image"].ToString(), 16, 16);
                     nbg.ItemLinks.Add(nbi);

                     if (firstItem == null)
                         firstItem = nbi;
                 });
                 //nbg.Expanded = true;
                 navBarControl1.Groups.Add(nbg);
             });
            if (this.navBarControl1.Groups.Count > 0)
                this.navBarControl1.Groups[0].Expanded = true;
            if (nbiFirst != null)
            {
                OpenChildForm(nbiFirst.Tag.ToString(), nbiFirst.Caption);
            }
        }
        /// <summary>
        /// 主菜单点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void nbg_LinkClicked(object sender, NavBarLinkEventArgs e)
        {
            try
            {
                NavBarItem nbi = e.Link.Item as NavBarItem;
                if (nbi == null || nbi.Tag == null || string.IsNullOrEmpty(nbi.Tag.ToString()))
                    return;
                OpenChildForm(nbi.Tag.ToString(), nbi.Caption);
            }
            catch (Exception ex)
            {
                UI.ShowError(ex.Message);
            }
        }
        /// <summary>
        /// 打开表单
        /// </summary>
        /// <param name="formId">表单ID，就是定义的Spring对象名不包含最后"Form"四个字母</param>
        /// <param name="formTitle"></param>
        public void OpenChildForm(string formCode, string text)
        {
            try
            {
                StartWaiting();
                string param = string.Empty;
                int i = formCode.IndexOf("?");
                if (i > 0)
                {
                    param = formCode.Substring(i + 1);
                    formCode = formCode.Substring(0, i);
                }
                //foreach (XtraMdiTabPage page in xtraTabbedMdiManager1.Pages)
                //{
                //    if (text == page.Text)
                //    {
                //        xtraTabbedMdiManager1.SelectedPage = page;
                //        return;
                //    }
                //}
                if (this.HasChildren && this.MdiChildren.Length > 0)
                {
                    if (this.MdiChildren[0].Text == text)
                    {
                        //if (text.Contains("LED"))
                        //{
                        //    if (this.MdiChildren.Length > 1)
                        //    {
                        //        return;
                        //    }
                        //}
                        //else
                        //{
                        return;
                        //}
                    }
                    else
                    {
                        this.MdiChildren[0].Close();
                    }
                }
                if (formCode.ToLower().StartsWith("reports"))
                {
                    //formCode = "ReportClass";
                    //var rpt = (ReportBase)(Assembly.GetExecutingAssembly().CreateInstance("Waker.Reports." + formCode, false));

                    //InitReport(rpt, text);
                    ////rpt.ShowPreview();

                    ////var PS = new DevExpress.XtraPrinting.PrintingSystem();
                    ////var CL = new DevExpress.XtraPrintingLinks.CompositeLink();
                    ////CL.PrintingSystem = PS;
                    ////var Lnk = new DevExpress.XtraPrinting.PrintableComponentLink();
                    //////Lnk.Component = GridData;
                    ////CL.Links.Add(Lnk);
                    ////CL.CreateDocument();


                    ////rpt.PrintingSystem = PS;
                    // Form1 f = new Form1();
                    var rpt = (ReportBase)(Assembly.GetExecutingAssembly().CreateInstance("Waker." + formCode, false));
                    if (rpt == null)
                        return;
                    rpt.InitReport(text);
                    Reports.FormReport f = new Reports.FormReport(rpt);
                    f.Text = text;
                    //f.Tag = param;
                    f.MdiParent = this;
                    f.WindowState = FormWindowState.Maximized;
                    f.ControlBox = false;
                    f.MaximizeBox = false;
                    f.MinimizeBox = false;
                    f.Resize += new EventHandler(f_Resize);
                    f.Show();
                }
                else
                {

                    var typeClass = Type.GetType(string.Format("Waker.{0}", formCode), false, false);
                    if (typeClass == null)
                        return;
                    var temp = Activator.CreateInstance(typeClass);
                    if (temp == null)
                        return;
                    var f = temp as FormBase;
                    if (f == null)
                        return;
                    f.Text = text;
                    //f.Tag = param; 
                    f.MdiParent = this;
                    f.WindowState = FormWindowState.Maximized;
                    f.ControlBox = false;
                    f.MaximizeBox = false;
                    f.MinimizeBox = false;
                    f.AutoScroll = true;
                    f.Resize += new EventHandler(f_Resize);
                    f.Show();
                }
            }
            catch (Exception ex)
            {
                UI.ShowError(ex.Message, "错误");
            }
            finally
            {
                EndWaiting();
            }
        }

        void f_Resize(object sender, EventArgs e)
        {
            var f = sender as Base.FormBase;
            if (f != null)
                f.WindowState = FormWindowState.Maximized;
        }



        #endregion

        #region 皮肤
        /// <summary>
        /// 加载皮肤
        /// </summary>
        private void BindSkins()
        {
            string[,] skins = new string[8, 2]{
                {"DevExpress Style", "默认"},
                {"Caramel", "咖啡棕"},
                {"Money Twins", "深海蓝"},
                {"Lilian", "青石蓝"},
                {"The Asphalt World", "夏日蓝"},
                {"iMaginary", "意境蓝"},
                {"Black", "魅力黑"},
                {"Blue", "爵士蓝"}
            };

            int si = 1;
            styleMenu.ItemLinks.Clear();
            for (int i = 0; i <= skins.GetUpperBound(0); i++)
            {
                BarCheckItem skinItem = new BarCheckItem();
                skinItem.Tag = skins[i, 0];
                skinItem.Caption = skins[i, si];
                skinItem.ItemClick += new ItemClickEventHandler(skinItem_ItemClick);
                if (skinItem.Tag.ToString() == Session._SkinName)
                {
                    skinItem.Checked = true;
                }
                styleMenu.AddItem(skinItem);
            }
            //foreach (DevExpress.Skins.SkinContainer skin in DevExpress.Skins.SkinManager.Default.Skins)
            //{
            //    BarCheckItem skinItem = new BarCheckItem();
            //    skinItem.Tag = skin.SkinName;
            //    skinItem.Caption = skin.SkinName;
            //    skinItem.ItemClick += new ItemClickEventHandler(skinItem_ItemClick);
            //    if (skinItem.Tag.ToString() == Session._SkinName)
            //    {
            //        skinItem.Checked = true;
            //    }
            //    styleMenu.AddItem(skinItem);
            //}
        }

        void skinItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            BarCheckItem menu = e.Item as BarCheckItem;

            foreach (BarItemLink mi in styleMenu.ItemLinks)
            {
                if (mi.Item.Tag.Equals(menu.Tag))
                {
                    ((BarCheckItem)mi.Item).Checked = true;
                }
                else
                {
                    ((BarCheckItem)mi.Item).Checked = false;
                }
            }
            //Session._DefaultLookAndFeel.LookAndFeel.SkinName = menu.Tag.ToString();
            //Util.SetRegValue("Style", menu.Tag);
            Session._SkinName = menu.Tag.ToString();
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName = Session._SkinName;
            new INIHelper(Consts.IniConfigPath).Writue("Skin", "SkinName", menu.Tag.ToString());
        }

        #endregion

        #region 计算器和记事本
        /// <summary>
        /// 计算器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem3_ItemClick(object sender, ItemClickEventArgs e)
        {
            Process.Start("calc");
        }
        /// <summary>
        /// 记事本
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem11_ItemClick(object sender, ItemClickEventArgs e)
        {
            Process.Start("notepad");
        }

        #endregion

        #region 锁定屏幕+修改密码+退出
        /// <summary>
        /// 锁定屏幕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barBtnLockSceen_ItemClick(object sender, ItemClickEventArgs e)
        {
            var f = new LockScreenForm();
            f.MainForm = this;
            f.ShowDialog();

        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barBtnChangPassword_ItemClick(object sender, ItemClickEventArgs e)
        {
            var f = new ChangePwdForm();
            f.ShowDialog();
        }
        /// <summary>
        /// 退出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barBtnQuit_ItemClick(object sender, ItemClickEventArgs e)
        {
            ExitSystem(true);
        }
        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!ExitSystem(true))
                e.Cancel = true;
        }
        protected internal bool ExitSystem(bool isCofirm)
        {
            if (isCofirm)
            {
                if (!UI.ShowOKCancelReturnBool(string.Format("确定要退出{0}?", Consts.System_Name)))
                {
                    return false;
                }
            }
            try
            {
                timerDeviceEvent.Enabled = timerDeviceSyncData.Enabled = timerCurrTime.Enabled = false;
                if (Session.Finger_IsConneted)
                    ZKTHelper.ZKTDisConnect();
                foreach (var kv in Session._DicADsDevice)
                {
                    var m = kv.Value.M_Comm;
                    ADSHalAPI.ADS_DisconnectController(ref Session._ADS_Comadapter, ref m);
                }
                if (Session.IDCard_IsConneted)
                    IDCardHelper.Syn_ClosePort(Session.IDCard_nPort);

                CardHelper.RC500USB_exit();
                foreach (var device in Session._DicADsDevice)
                {
                    var m = device.Value.M_Comm;
                    ADSHalAPI.ADS_DisconnectController(ref Session._ADS_Comadapter, ref m);
                }
                ADSHalAPI.ADS_CloseComAdapter(ref Session._ADS_Comadapter);

                HCNetSDK.NET_DVR_Cleanup();
            }

            catch (Exception e)
            {
                new Loger().LogException(e);
            }
            finally
            {
                Application.ExitThread();
            }
            return false;
        }
        #endregion

        #region  工具栏选中改变+状态栏选中改变+导航图+导航菜单选中改变
        /// <summary>
        /// 工具栏选中改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barChkTool_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            this.barTool.Visible = barChkTool.Checked;
        }
        /// <summary>
        /// 状态栏选中改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barChkStatus_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            this.barStatus.Visible = barChkStatus.Checked;
        }
        /// <summary>
        /// 实时刷卡列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barChkEvent_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            this.dpEvent.Visibility = barChkEvent.Checked ? DockVisibility.Visible : DockVisibility.Hidden;
        }
        /// <summary>
        /// 导航图
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barBtnNavigation_ItemClick(object sender, ItemClickEventArgs e)
        {

        }
        /// <summary>
        /// 导航菜单选中改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barChkMenu_CheckedChanged(object sender, ItemClickEventArgs e)
        {
            //navBarControl1.Visible = barChkMenu.Checked;
            dpMenu.Visibility = barChkMenu.Checked ? DockVisibility.Visible : DockVisibility.AutoHide;
        }
        #endregion

        #region  联系我们+关于
        /// <summary>
        /// 联系我们
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barBtnContact_ItemClick(object sender, ItemClickEventArgs e)
        {

        }
        /// <summary>
        /// 关于
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barBtnAbout_ItemClick(object sender, ItemClickEventArgs e)
        {

        }
        #endregion

        #region  时间定时器
        /// <summary>
        /// 时间定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerCurrTime_Tick(object sender, EventArgs e)
        {
            barTxtTime.Caption = DateTime.Now.ToString(Consts.StrDateTimeFormat);
        }
        #endregion

        #region 初始化
        private void InitData()
        {
            try
            {
                var ini = new INIHelper(Consts.IniConfigPath);
                var s = ini.ReadValue("CardConfig", "IsCardUse34");
                if (string.IsNullOrEmpty(s))
                {
                    Session.IsCardUse34 = true;
                    ini.Writue("CardConfig", "IsCardUse34", Session.IsCardUse34.ToString());
                }
                else
                {
                    Session.IsCardUse34 = Convert.ToBoolean(s);
                }
                this.timerDeviceSyncData.Interval = Consts.TimerDevieSyncDataInterval;
                this.timerDeviceEvent.Interval = Consts.TimerDeviceEventInterval;


                Session.ListEmployeeAndCard = new BAL_Cards().GetAllEmployeeAndCard();

                var bal = new BAL.BAL_SystemSetting();
                var tempName = bal.GetCommanyInfo("Name");
                Session._CommanyName = tempName == DBNull.Value ? string.Empty : tempName.ToString();
                var temp = bal.GetCommanyInfo("Logo");
                Session._CommanyLogo = temp == DBNull.Value ? null : (byte[])temp;


                //if (!ConfigurationManager.AppSettings.AllKeys.Contains("IsCardUse34"))
                //{
                //    Session.IsCardUse34 = true;                     
                //    ConfigurationManager.OpenExeConfiguration(AppDomain.CurrentDomain.BaseDirectory).AppSettings

                //        ("IsCardUse34", Session.IsCardUse34.ToString());
                //}
                //else
                //{
                //    if (!bool.TryParse(ConfigurationManager.AppSettings["IsCardUse34"].ToString(), out Session.IsCardUse34))
                //    {
                //        Session.IsCardUse34 = true;
                //        ConfigurationManager.AppSettings.Set("IsCardUse34", Session.IsCardUse34.ToString());
                //    }
                //}

                if (File.Exists(Consts.SysIocnPath))
                {
                    this.Icon = new Icon(Consts.SysIocnPath);
                }
                ThreadPool.SetMinThreads(200, 500);
                ThreadPool.SetMaxThreads(2000, 5000);
            }
            catch (Exception ex)
            {
                new Loger().LogException(ex);
            }
        }
        private void InitZKTFinger()
        {
            try
            {
                var ini = new INIHelper(Consts.IniConfigPath);
                var ip = ini.ReadValue("Finger", "IP");
                Session.Finger_IP = string.IsNullOrEmpty(ip) ? "192.168.1.201" : ip;
                int port;
                if (int.TryParse(ini.ReadValue("Finger", "Port"), out port))
                    Session.Finger_Port = port;
                else
                    Session.Finger_Port = 4370;
                //先ping ip 如果存在在连接
                if (IPHelper.TestNetConnected(ip, 1, 3))
                {
                    //var help = new ZKTHelper();
                    Session.Finger_IsConneted = ZKTHelper.ZKTConnect().IsSuccess;
                    if (Session.Finger_IsConneted)
                    {
                        ZKTHelper.ZKTEnableDevice(true);
                        ZKTHelper.ZKTSetUserInfo("管理员", 88888, "12345", 3, true);
                        var res = ZKTHelper.ZKTGetDeviceStatus(12);
                        if (res.IsSuccess && res.ResultData > 10)
                            ZKTHelper.ZKTClearData(1);
                        res = ZKTHelper.ZKTGetDeviceStatus(5);
                        if (res.IsSuccess && res.ResultData > 90)
                            ZKTHelper.ZKTClearData(4);
                        //ZKTHelper.ZKTPowerOffDevice();
                        ZKTHelper.ZKTSetDeviceTime();
                        ZKTHelper.ZKTDisConnect();
                    }
                    //}); 
                }
            }
            catch (Exception ex)
            {
                new Loger().LogException(ex);
            }
        }
        private void InitIDCard()
        {
            try
            {
                ThreadPool.QueueUserWorkItem((obj) =>
                {
                    int nPort;
                    if (int.TryParse(new INIHelper(Consts.IniConfigPath).ReadValue("IDCards", "nPort"), out nPort))
                        Session.IDCard_nPort = nPort;
                    var resMsg = string.Empty;
                    var helper = new IDCardHelper();
                    Session.IDCard_IsConneted = helper.SearchReader(out resMsg);
                });
            }
            catch
            { }
        }
        public void InitADS()
        {
            // ThreadPool.QueueUserWorkItem((obj) =>
            //{
            try
            {
                Session._DicADsDevice.Clear();
                Session._ADS_Comadapter.type = (byte)ADSHalConstant.ADS_COMAdapterType.ADS_ADT_TCP;
                Session._ADS_Comadapter.address = 0;
                Session._ADS_Comadapter.port = 0;
                var ds = new BAL.BAL_Device().GetDeviceAll();
                if (ds != null && ds.Tables.Count > 2)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        var enADs = new En_ADS();
                        var m_comm = new ADSHalDataStruct.ADS_CommunicationParameter();
                        m_comm.deviceAddr = ADSHelp.IP2Int(dr["ComAdapter_Addr"].ToString());
                        m_comm.devicePort = (ushort)(Convert.ToUInt16(dr["ComAdapter_Port"].ToString()));
                        m_comm.password = (ushort)(Convert.ToUInt16(dr["ComAdapter_pwd"].ToString()));
                        enADs.M_Comm = m_comm;
                        enADs.Device_ID = dr["Device_ID"].ToString();
                        enADs.Device_Name = dr["Device_Name"].ToString();
                        enADs.ListSub = new List<En_ADSSub>();
                        if (ds.Tables[1] != null && ds.Tables[1].Rows.Count > 0)
                        {
                            var drs = ds.Tables[1].Select(string.Format("Device_ID='{0}'", dr["Device_ID"]));
                            if (drs.Length > 0)
                            {
                                foreach (DataRow drSub in drs)
                                {
                                    var enSub = new En_ADSSub();
                                    ADSHalDataStruct.ADS_LogicSubDeviceInformation subLogic = new ADSHalDataStruct.ADS_LogicSubDeviceInformation();
                                    subLogic.logicSubDeviceAddrNumber = new ADSHalDataStruct.ADS_LogicSubDeviceAddress();
                                    subLogic.logicSubDeviceAddrNumber.physicalSubDevAddr = 0;
                                    subLogic.logicSubDeviceAddrNumber.logicSubDevNumber = Convert.ToByte(drSub["Physics_ID"]);
                                    subLogic.logicSubDeviceCategory = Convert.ToByte(drSub["LSubDevice_Type"]);

                                    enSub.Physics_ID = Convert.ToByte(drSub["Physics_ID"]);
                                    enSub.LSubDevice_Name = drSub["LSubDevice_Name"].ToString();
                                    enSub.LSubDevice_ID = drSub["LSubDevice_ID"].ToString();

                                    enSub.IsUseNVR = Convert.ToBoolean(drSub["IsUseNVR"]);
                                    //if (drSub["NVR_ID"] != DBNull.Value)
                                    //{
                                    //    enSub.NVR_ID = Convert.ToInt32(drSub["NVR_ID"]);
                                    //enSub.NVRIp = drSub["NVR_IP"].ToString();
                                    //enSub.NVRPort = Convert.ToInt32(drSub["NVR_Port"]);
                                    //enSub.NVRChannel = Convert.ToInt32(drSub["NVRChannel"]);
                                    //enSub.NVRUsrName = drSub["NVR_UserName"].ToString();
                                    //enSub.NVRPwd = drSub["NVR_Pwd"].ToString();
                                    //}
                                    //if (enSub.IsUseNVR && enSub.NVR_ID > 0)
                                    if (enSub.IsUseNVR)
                                    {
                                        enSub.NVRIp = drSub["NVRIp"].ToString();
                                        enSub.NVRPort = Convert.ToInt32(drSub["NVRPort"]);
                                        enSub.NVRChannel = Convert.ToInt32(drSub["NVRChannel"]);
                                        enSub.NVRUsrName = drSub["NVRUsrName"].ToString();
                                        enSub.NVRPwd = drSub["NVRPwd"].ToString();
                                        if (!Session.IsNVRInited)
                                            InitNVR();
                                        if (Session.IsNVRInited)
                                        {
                                            enSub.LonginUserID = -1;
                                            for (int i = 0; i < 3; i++)
                                            {
                                                enSub.LonginUserID = HCNetSDK.NET_DVR_Login_V30(
                                                       enSub.NVRIp,
                                                      (ushort)enSub.NVRPort,
                                                      enSub.NVRUsrName,
                                                       enSub.NVRPwd,
                                                       out _NVR_DeviceInfo);
                                                if (enSub.LonginUserID != -1)
                                                    break;
                                            }
                                        }
                                    }
                                    enADs.ListSub.Add(enSub);
                                    #region 不用
                                    //if (drSub["IsUseNVR"] != DBNull.Value && Convert.ToBoolean(drSub["IsUseNVR"]))
                                    //{
                                    //    //lUserID = HCNetSDK.NET_DVR_Login_V30("192.168.0.205", 8000, "admin", "12345", out dev);

                                    //    lUserID = HCNetSDK.NET_DVR_Login_V30(
                                    //        drSub["NVRIp"].ToString(),
                                    //       (ushort)drSub["NVRPort"],
                                    //       drSub["NVRUsrName"].ToString(),
                                    //        drSub["NVRPwd"].ToString(),
                                    //        out _NVR_DeviceInfo);
                                    //    if (lUserID != -1)
                                    //    {
                                    //        var enNvr = new En_NVR();
                                    //        enNvr.DeviceID = dr["Device_ID"].ToString();

                                    //        enNvr.LSubDeviceID = drSub["LSubDevice_ID"].ToString();
                                    //        enNvr.IsUseNVR = Convert.ToBoolean(drSub["IsUseNVR"]);

                                    //        enNvr.NVRIp = drSub["NVRIp"].ToString();
                                    //        enNvr.NVRPort = Convert.ToInt32(drSub["NVRPort"]);
                                    //        enNvr.NVRChannel = Convert.ToByte(drSub["NVRChannel"]);
                                    //        enNvr.NVRUsrName = drSub["NVRUsrName"].ToString();
                                    //        enNvr.NVRUsrName = drSub["NVRPwd"].ToString();
                                    //        enNvr.LonginUserID = lUserID;

                                    //        Session._DioLoginedNVR.Add(
                                    //    string.Format("{0}.{1}", dr["Device_ID"], drSub["LSubDevice_ID"])
                                    //    , enNvr);
                                    //    }
                                    //}
                                    #endregion
                                }
                            }
                        }
                        Session._DicADsDevice.Add(dr["Device_ID"].ToString(), enADs);
                    }
                }
            }
            catch (Exception ex)
            {
                var log = new Loger();
                log.Log("初始化门禁设备错误,错误信息:");
                log.LogException(ex);
            }
            //}); 
        }
        public void InitNVR()
        {
            try
            {
                //this.pictureEdit1.Image = Session.EventImage;
                Session.IsNVRInited = HCNetSDK.NET_DVR_Init();
                HCNetSDK.NET_DVR_SetConnectTime(5000, 1);


                //_NVR_JpgPara.wPicQuality = 2;
                //_NVR_JpgPara.wPicSize = 6;
            }
            catch (Exception ex)
            {
                new Loger().LogException(ex);
            }
        }
        public void InitLEDInDoor()
        {
            if (File.Exists(Consts.LEDInDoorXmlPath))
            {
                var xd = new System.Xml.XmlDocument();
                xd.Load(Consts.LEDInDoorXmlPath);
                Session.ListInDoorLEDData = XmlHelper<En_LEDData>.XmlToEntityList(xd.InnerXml).ToList();
            }
            if (Screen.AllScreens.Length < Consts.LEDInDoorScreenIndex + 1)
                return;
            if (Session.ListInDoorLEDData.Count < 1)
                return;
            //var screen = Screen.AllScreens[Consts.LEDInDoorScreenIndex]; 
            //FormLEDInDoorDisplay fLED = new FormLEDInDoorDisplay();
            var fLED = new FormLEDInDoorDisplayNew();
            fLED.Show();
            this.Location = new Point(0, 0);
        }
        #endregion

        #region 同步数据
        private void timerDeviceSyncData_Tick(object sender, EventArgs e)
        {
            //barBtnSyncData_ItemClick(null, null);
            try
            {
                StartWaiting("正在同步数据,请稍侯");
                var ThreadSyncData = new Thread(new ThreadStart(() =>
                {
                    //ThreadPool.QueueUserWorkItem((obj) =>
                    //{
                    SyncData();
                    //});
                }));
                ThreadSyncData.IsBackground = true;
                ThreadSyncData.Start();
                SyncStaffToFinger();
            }
            catch (Exception ex)
            {
                var log = new Loger();
                log.Log("同步数据错误,错误信息:");
                log.LogException(ex);
            }
            finally
            {
                EndWaiting();
            }
        }
        private void barBtnSyncData_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                StartWaiting("正在同步数据,请稍侯");
                //var ThreadSyncData = new Thread(new ThreadStart(() =>
                //{
                //ThreadPool.QueueUserWorkItem((obj) =>
                //{
                SyncData();
                //});
                //}));
                //ThreadSyncData.IsBackground = true;
                //ThreadSyncData.Start();
                SyncStaffToFinger();
            }
            catch (Exception ex)
            {
                var log = new Loger();
                log.Log("同步数据错误,错误信息:");
                log.LogException(ex);
            }
            finally
            {
                EndWaiting();
            }
        }
        public void SyncData()
        {
            var log = new Loger();
            log.Log(string.Format("同步门禁数据开始{0}", DateTime.Now));
            SyncTimePriodToDevice();
            SyncSubContractorToDevice();
            SyncStaffToDevice();
            SyncDoorPerssionToDevice();
            log.Log(string.Format("同步门禁数据结束{0}", DateTime.Now));
        }
        public void SyncTimePriodToDevice()
        {
            try
            {
                var dt = new BAL.BAL_Cards().GetTableByTableName("T_TimePeriod");
                if (dt == null || dt.Rows.Count < 1)
                    return;
                int iResult = -1;
                var bal = new BAL_Cards();
                ADSHalDataStruct.ADS_CommunicationParameter com;
                foreach (var kv in Session._DicADsDevice)
                {
                    com = kv.Value.M_Comm;
                    for (int i = 0; i < 3; i++)
                    {
                        iResult = ADSHalAPI.ADS_ConnectController(ref Session._ADS_Comadapter, ref com);
                        if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                            break;
                    }
                    if (iResult != (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                        continue;

                    var maxTimerId = Convert.ToUInt32(bal.GetNextId("T_TimePeriod", "TimePeriod_ID"));
                    if (maxTimerId > 0)
                    {
                        for (UInt32 index = 1; index < maxTimerId && index < 253; index++)
                        {
                            for (int i = 0; i < 3; i++)
                            {
                                //iResult = ADSHalAPI.ADS_ClearTimePeriodGroup(ref Session._ADS_Comadapter, ref com);
                                iResult = ADSHalAPI.ADS_DeleteTimePeriodGroup(ref Session._ADS_Comadapter, ref com, index);
                                if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                    break;
                            }
                        }
                    }

                    //foreach (var sub in kv.Value.dicLogicSubDeviceInformation)
                    //{
                    var drs = dt.Select(string.Format("Device_ID='{0}'", kv.Key));
                    if (drs.Length < 1)
                        continue;

                    ADSHalDataStruct.ADS_TimePeriodGroup m_timePeriodGroup = new ADSHalDataStruct.ADS_TimePeriodGroup();
                    m_timePeriodGroup.timePeriods = new ADSHalDataStruct.ADS_TimePeriod[10];
                    //m_timePeriodGroup.ID = 1;
                    m_timePeriodGroup.holidayGroupID = 0;
                    m_timePeriodGroup.count = Convert.ToByte(drs.Length);

                    for (int i = 0; i < 10; i++)
                    {
                        if (i > drs.Length - 1)
                            break;
                        var dr = drs[i];
                        m_timePeriodGroup.timePeriods[i].Init();

                        //task.ID = Convert.ToByte(dr["TimePeriod_ID"]);
                        //task.logicSubDeviceAddress.logicSubDevNumber = sub.Value.logicSubDeviceAddrNumber.logicSubDevNumber;
                        //task.logicSubDeviceAddress.physicalSubDevAddr = sub.Value.logicSubDeviceAddrNumber.physicalSubDevAddr;



                        var dateStart = Convert.ToDateTime(dr["BeginDate"]);
                        m_timePeriodGroup.timePeriods[i].startDate = new ADSHalDataStruct.ADS_YMD();
                        m_timePeriodGroup.timePeriods[i].startDate.year = Convert.ToByte(dateStart.Year - 2000);
                        m_timePeriodGroup.timePeriods[i].startDate.month = Convert.ToByte(dateStart.Month);
                        m_timePeriodGroup.timePeriods[i].startDate.day = Convert.ToByte(dateStart.Day);

                        var dateEnd = Convert.ToDateTime(dr["EndDate"]);
                        m_timePeriodGroup.timePeriods[i].endDate = new ADSHalDataStruct.ADS_YMD();
                        m_timePeriodGroup.timePeriods[i].endDate.year = Convert.ToByte(dateEnd.Year - 2000);
                        m_timePeriodGroup.timePeriods[i].endDate.month = Convert.ToByte(dateEnd.Month);
                        m_timePeriodGroup.timePeriods[i].endDate.day = Convert.ToByte(dateEnd.Day);

                        m_timePeriodGroup.timePeriods[i].Init();
                        for (int j = 0; j < 5; j++)
                        {
                            var timeStart = Convert.ToDateTime(dr["StartTime" + i.ToString()]);
                            m_timePeriodGroup.timePeriods[i].startTimes[j] = new ADSHalDataStruct.ADS_HMS();
                            m_timePeriodGroup.timePeriods[i].startTimes[j].hour = Convert.ToByte(timeStart.Hour);
                            m_timePeriodGroup.timePeriods[i].startTimes[j].minute = Convert.ToByte(timeStart.Minute);
                            m_timePeriodGroup.timePeriods[i].startTimes[j].sec = Convert.ToByte(timeStart.Second);

                            var timeEnd = Convert.ToDateTime(dr["Endtime" + i.ToString()]);
                            m_timePeriodGroup.timePeriods[i].endTimes[j] = new ADSHalDataStruct.ADS_HMS();
                            m_timePeriodGroup.timePeriods[i].endTimes[j].hour = Convert.ToByte(timeEnd.Hour);
                            m_timePeriodGroup.timePeriods[i].endTimes[j].minute = Convert.ToByte(timeEnd.Minute);
                            m_timePeriodGroup.timePeriods[i].endTimes[j].sec = Convert.ToByte(timeEnd.Second);
                        }

                        m_timePeriodGroup.timePeriods[i].validWeek = Convert.ToByte(dr["ValidWeek"]);

                        m_timePeriodGroup.ID = Convert.ToByte(dr["TimePeriod_ID"]);
                        m_timePeriodGroup.holidayGroupID = 0;
                    }
                    for (int t = 0; t < 3; t++)
                    {
                        iResult = ADSHalAPI.ADS_SetTimePeriodGroup(ref Session._ADS_Comadapter, ref com, ref m_timePeriodGroup);
                        if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                            break;
                    }
                    //}
                }
            }
            catch (Exception ex)
            {
                var log = new Loger();
                log.Log("同步时段到门禁设备出错,错误信息:");
                log.LogException(ex);
                return;
            }
        }
        public void SyncSubContractorToDevice()
        {
            try
            {
                var bal = new BAL_Cards();
                var ds = bal.GetNoUploadSubContractor();
                if (ds == null)
                    return;
                int iResult = -1;
                foreach (DataRow dr in ds.Tables["tbDeletedDepartment"].Rows)
                {
                    if (dr["Dept_No"] == DBNull.Value || Convert.ToInt32(dr["Dept_No"]) < 1)
                        continue;
                    ADSHalDataStruct.ADS_CommunicationParameter com;
                    foreach (var m in Session._DicADsDevice.Values)
                    {
                        com = m.M_Comm;
                        for (int i = 0; i < 3; i++)
                        {
                            iResult = ADSHalAPI.ADS_ConnectController(ref Session._ADS_Comadapter, ref com);
                            if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                break;
                        }
                        if (iResult != (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                            continue;

                        for (int i = 0; i < 3; i++)
                        {
                            iResult = ADSHalAPI.ADS_DeleteDepartment(ref Session._ADS_Comadapter, ref com, Convert.ToUInt16(dr["Dept_No"]));
                            if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                break;
                        }

                        if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                        {
                            for (int i = 0; i < 3; i++)
                            {
                                iResult = ADSHalAPI.ADS_DeletePermission(ref Session._ADS_Comadapter, ref com, Convert.ToUInt32(dr["Dept_No"]));
                                if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                    break;
                            }
                            if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                            {
                                //var isOk =
                                bal.SetSubContractorDeletedUpload(dr["SerialNumber"].ToString(), true);
                            }
                        }
                    }
                }

                foreach (DataRow dr in ds.Tables["tbDepartment"].Rows)
                {
                    ADSHalDataStruct.ADS_CommunicationParameter com;
                    foreach (var device in Session._DicADsDevice.Values)
                    {
                        com = device.M_Comm;
                        for (int i = 0; i < 3; i++)
                        {
                            iResult = ADSHalAPI.ADS_ConnectController(ref Session._ADS_Comadapter, ref com);
                            if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                break;
                        }
                        if (iResult != (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                            continue;
                        var d = new ADSHalDataStruct.ADS_Department();
                        if (dr["Dept_No"] == DBNull.Value || Convert.ToInt32(dr["Dept_No"]) < 1)
                            continue;

                        for (int i = 0; i < 3; i++)
                        {
                            iResult = ADSHalAPI.ADS_GetDepartment(ref Session._ADS_Comadapter, ref com, ref d);
                            if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                break;
                        }
                        if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS && d.ID > 0)
                            continue;
                        d.ID = Convert.ToUInt16(dr["Dept_No"]);

                        //else
                        //{
                        //d.ID = Convert.ToUInt16(bal.GetNextId("tbDepartment", "Dept_No"));
                        //}
                        d.superiorID = 0;
                        for (int i = 0; i < 3; i++)
                        {
                            iResult = ADSHalAPI.ADS_SetDepartment(ref Session._ADS_Comadapter, ref com, ref d);
                            if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                break;
                        }
                        if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                        {
                            //foreach (var sub in device.ListSub)
                            //{
                            //    ADSHalDataStruct.ADS_Permission per = new ADSHalDataStruct.ADS_Permission();
                            //    per.ID = Convert.ToUInt32(d.ID);
                            //    per.logicSubDeviceAddress = new ADSHalDataStruct.ADS_LogicSubDeviceAddress() { logicSubDevNumber = sub.Physics_ID, physicalSubDevAddr = 0 };
                            //    per.readerPos = Convert.ToByte(ADSHalConstant.ADS_ReaderPosition.ADS_RP_BOTH);
                            //    per.isCardNumber = 0;
                            //    per.departID = d.ID;
                            //    per.Init();
                            //    per.reserve[0] = 0;
                            //    per.reserve[1] = 0;
                            //    per.actionPortMask = Convert.ToUInt32(ADSHalConstant.ADS_IOM_DOOR);
                            //    per.actionPortState = Convert.ToUInt32(ADSHalConstant.ADS_IOM_DOOR);
                            //    per.timePeriodGroupID = 254;
                            //    for (int i = 0; i < 3; i++)
                            //    {
                            //        iResult = ADSHalAPI.ADS_SetPermission(ref Session._ADS_Comadapter, ref com, ref per);
                            //        if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                            //            break;
                            //    }
                            //}
                            //if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                            //{

                            //    bal.SetSubContractorUpload(dr["Dept_ID"].ToString(), d.ID, true);
                            //}
                        }
                    }
                }
                return;
            }
            catch (Exception ex)
            {
                var log = new Loger();
                log.Log("同步分包商到门禁设备出错,错误信息:");
                log.LogException(ex);
                return;
            }
        }
        public void SyncStaffToDevice()
        {
            try
            {
                var bal = new BAL_Cards();
                var ds = bal.GetNoUploadDeviceEmployee();
                if (ds == null)
                    return;

                int iResult = -1;
                foreach (DataRow dr in ds.Tables["tbEmp_Card_DeletedAndLeave"].Rows)
                {
                    ADSHalDataStruct.ADS_CommunicationParameter com;
                    foreach (var m in Session._DicADsDevice.Values)
                    {
                        com = m.M_Comm;
                        for (int i = 0; i < 3; i++)
                        {
                            iResult = ADSHalAPI.ADS_ConnectController(ref Session._ADS_Comadapter, ref com);
                            if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                break;
                        }
                        if (iResult != (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                            continue;
                        ADSHalDataStruct.ADS_CardHolder card = new ADSHalDataStruct.ADS_CardHolder();
                        card.cardNumber.LoNumber = Util.GetCardNoByWigan(Convert.ToUInt32(dr["Card_No"]));
                        card.cardNumber.HiNumber = 0;

                        for (int i = 0; i < 3; i++)
                        {
                            iResult = ADSHalAPI.ADS_DeleteCardHolder(ref Session._ADS_Comadapter, ref com, ref card);
                            if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                break;
                        }
                        if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                        {
                            bal.SetEmployeeCardUploadDevice(dr["Emp_Card_ID"].ToString(), true);
                        }
                    }
                }
                foreach (DataRow dr in ds.Tables["tbEmp_Card"].Rows)
                {
                    ADSHalDataStruct.ADS_CommunicationParameter com;
                    foreach (var m in Session._DicADsDevice.Values)
                    {
                        com = m.M_Comm;
                        //ADSHalDataStruct.ADS_CardHolder card = new ADSHalDataStruct.ADS_CardHolder();
                        //card.cardNumber.LoNumber = Convert.ToUInt32(dr["Card_No"]);
                        //card.cardNumber.HiNumber = 0;
                        for (int i = 0; i < 3; i++)
                        {
                            iResult = ADSHalAPI.ADS_ConnectController(ref Session._ADS_Comadapter, ref com);
                            if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                break;
                            //iResult = ADSHalAPI.ADS_GetCardHolder(ref Session._ADS_Comadapter, ref com, ref card);

                        }
                        if (iResult != (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                            continue;
                        ADSHalDataStruct.ADS_CardHolder card = new ADSHalDataStruct.ADS_CardHolder();
                        //card.Init();
                        //var name = dr["Emp_Name"].ToString();
                        //for (int i = 0; (i < card.name.Length); i++)
                        //{
                        //    if (i < name.Length)
                        //        card.name[i] = name[i];
                        //    else
                        //        card.name[i] = ' ';
                        //}
                        //card.name = (name.Length > 8 ? name.Substring(0, 8) : name).ToArray();
                        card.cardNumber.LoNumber = Util.GetCardNoByWigan(Convert.ToUInt32(dr["Card_No"]));
                        card.cardNumber.HiNumber = 0;
                        card.password = dr["Card_Password"] == DBNull.Value ? 0 : Convert.ToUInt32(dr["Card_Password"]);
                        card.departmentID = (ushort)(dr["Dept_No"] == DBNull.Value ? 0 : Convert.ToInt32(dr["Dept_No"]));
                        card.groupNumber = Convert.ToByte(ADSHalConstant.ADS_CardGroupType.ADS_CGT_GENERAL);
                        //card.curAPBArea = 0;
                        if (dr["Card_ExpireDate"] != DBNull.Value)
                        {
                            var date = Convert.ToDateTime(dr["Card_ExpireDate"]);
                            card.expirationDate = new ADSHalDataStruct.ADS_YMDHMS();
                            card.expirationDate.year = (byte)(date.Year - 2000);
                            card.expirationDate.month = (byte)date.Month;
                            card.expirationDate.day = (byte)date.Day;
                            card.expirationDate.hour = (byte)date.Hour;
                            card.expirationDate.minute = (byte)date.Minute;
                            card.expirationDate.sec = (byte)date.Second;
                        }
                        uint uRetCount = 0;

                        for (int i = 0; i < 3; i++)
                        {
                            iResult = ADSHalAPI.ADS_SetCardHolders(ref Session._ADS_Comadapter, ref com, ref card, 1, ref uRetCount);
                            if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                break;
                        }
                        if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                        {
                            bal.SetEmployeeCardUploadDevice(dr["Emp_Card_ID"].ToString(), true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var log = new Loger();
                log.Log("同步用户到门禁设备出错,错误信息:");
                log.LogException(ex);
                return;
            }
        }
        public void SyncDoorPerssionToDevice()
        {
            try
            {
                var bal = new BAL_Cards();
                var ds = bal.GetNoLoadDoorPerssion();
                if (ds == null)
                    return;

                int iResult = -1;
                //已经删除的权限
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    ADSHalDataStruct.ADS_CommunicationParameter com;
                    foreach (var m in Session._DicADsDevice.Values)
                    {
                        if (dr["Device_ID"] == DBNull.Value || m.Device_ID != dr["Device_ID"].ToString())
                            continue;
                        com = m.M_Comm;
                        for (int i = 0; i < 3; i++)
                        {
                            iResult = ADSHalAPI.ADS_ConnectController(ref Session._ADS_Comadapter, ref com);
                            if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                break;
                        }
                        if (iResult != (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                            continue;
                        for (int i = 0; i < 3; i++)
                        {
                            iResult = ADSHalAPI.ADS_DeletePermission(ref Session._ADS_Comadapter, ref com, Convert.ToUInt32(dr["Permission_ID"]));
                            if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                break;
                        }
                        if (iResult != (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                        {
                            var log = new Loger();
                            log.Log(string.Format("删除门权限失败:失败权限id:{0},设备ip:{1},原因code:{2}", dr["Permission_ID"], ADSHelp.Int2IP(com.deviceAddr), iResult));
                        }
                    }
                }
                //设置权限
                foreach (DataRow dr in ds.Tables[1].Rows)
                {
                    ADSHalDataStruct.ADS_CommunicationParameter com;
                    foreach (var m in Session._DicADsDevice.Values)
                    {
                        if (dr["Device_ID"] == DBNull.Value || m.Device_ID != dr["Device_ID"].ToString())
                            continue;
                        com = m.M_Comm;
                        for (int i = 0; i < 3; i++)
                        {
                            iResult = ADSHalAPI.ADS_ConnectController(ref Session._ADS_Comadapter, ref com);
                            if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                break;
                        }
                        if (iResult != (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                            continue;
                        foreach (var sub in m.ListSub)
                        {
                            if (dr["LSubDevice_ID"] == DBNull.Value || sub.LSubDevice_ID != dr["LSubDevice_ID"].ToString()
                                || dr["Card_No"] == DBNull.Value
                                )
                                continue;
                            ADSHalDataStruct.ADS_Permission per = new ADSHalDataStruct.ADS_Permission();
                            per.ID = Convert.ToUInt32(dr["Permission_ID"]);
                            per.logicSubDeviceAddress = new ADSHalDataStruct.ADS_LogicSubDeviceAddress() { logicSubDevNumber = sub.Physics_ID, physicalSubDevAddr = 0 };
                            per.readerPos = Convert.ToByte(ADSHalConstant.ADS_ReaderPosition.ADS_RP_BOTH);
                            per.timePeriodGroupID = 1;
                            per.isCardNumber = 1;
                            per.departID = (ushort)(dr["Dept_No"] == DBNull.Value ? 0 : Convert.ToInt32(dr["Dept_No"]));
                            per.Init();
                            per.reserve[0] = 0;
                            per.reserve[1] = 0;
                            per.cardNumber.LoNumber = Util.GetCardNoByWigan(Convert.ToUInt32(dr["Card_No"]));
                            per.cardNumber.HiNumber = 0;

                            per.actionPortMask = 0;
                            per.actionPortState = 0;
                            per.actionPortMask |= Convert.ToUInt32(ADSHalConstant.ADS_IOM_DOOR);
                            per.actionPortState |= Convert.ToUInt32(ADSHalConstant.ADS_IOM_DOOR);
                            //per.timePeriodGroupID = 254;
                            for (int i = 0; i < 3; i++)
                            {
                                iResult = ADSHalAPI.ADS_SetPermission(ref Session._ADS_Comadapter, ref com, ref per);
                                if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                    break;
                            }
                            if (iResult != (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                            {
                                var log = new Loger();
                                log.Log(string.Format("设置门权限失败:失败权限id:{0},卡号:{1},设备ip{2},原因code:{3}", per.ID, dr["Card_No"], ADSHelp.Int2IP(com.deviceAddr), iResult));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var log = new Loger();
                log.Log("同步用户权限到门禁设备出错,错误信息:");
                log.LogException(ex);
            }
        }
        public En_Result SyncStaffToFinger()
        {
            try
            {
                var bal = new BAL_Cards();
                var ds = bal.GetNoUploadFingerEmployee();
                if (ds == null)
                    return En_Result.CreateFailedResult("读取要同步的员工数据失败");
                //先ping ip 如果存在在连接
                if (!IPHelper.TestNetConnected(Session.Finger_IP, 1, 3))
                {
                    new Loger().LogException("同步指纹机数据失败,指纹机ping不通");
                    return En_Result.CreateFailedResult("读取要同步的员工数据失败,指纹机ping不通");
                }
                var res = new En_Result();
                foreach (DataRow dr in ds.Tables["tbDeleted_Employee"].Rows)
                {
                    int fingerId = Convert.ToInt32(dr["FingerId"]);
                    if (fingerId < 1)
                        continue;
                    res = ZKTHelper.ZKTDeleteEnrollData(fingerId);
                    if (res.IsSuccess)
                    {
                        bal.SetEmployeeDeletedUploadFinger(dr["SerialNumber"].ToString(), true);
                    }
                }
                foreach (DataRow dr in ds.Tables["tbEmployeeLeave"].Rows)
                {
                    int fingerId = Convert.ToInt32(dr["FingerId"]);
                    if (fingerId < 1)
                        continue;
                    res = ZKTHelper.ZKTEnableUser(fingerId, false);
                    if (res.IsSuccess)
                    {
                        bal.UpdateEmployeeFingerId(dr["Emp_ID"].ToString(), fingerId);
                    }
                }

                foreach (DataRow dr in ds.Tables["tbEmployee"].Rows)
                {
                    int fingerId = 0;
                    if (Convert.ToInt32(dr["FingerId"]) < 1)
                        fingerId = bal.GetNextFingerId();
                    else
                    {
                        fingerId = Convert.ToInt32(dr["FingerId"]);

                        string name = string.Empty;
                        string pwd = string.Empty;
                        int privilege = -1;
                        bool enable = false;
                        res = ZKTHelper.ZKTGetUserInfo(fingerId, ref name, ref pwd, ref privilege, ref enable);
                        if (res.IsSuccess)
                        {
                            if (name == dr["Emp_Name"].ToString() && enable)
                                continue;
                        }
                    }
                    res = ZKTHelper.ZKTSetUserInfo(
                        dr["Emp_Name"].ToString(),
                        fingerId,
                        dr["FingerPwd"] == DBNull.Value ? string.Empty : dr["FingerPwd"].ToString(),
                        0,
                        true);
                    if (res.IsSuccess)
                    {
                        bal.UpdateEmployeeFingerId(dr["Emp_ID"].ToString(), fingerId);
                    }
                }
                return En_Result.CreateSuccessResult();
            }
            catch (Exception ex)
            {
                var log = new Loger();
                log.Log("同步用户到指纹机出错,错误信息:");
                log.LogException(ex);
                return En_Result.CreateFailedResult(ex.Message);
            }
        }
        #endregion

        #region 获取打卡记录
        private void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator)
            {
                e.Info.DisplayText = Convert.ToString(e.RowHandle + 1);
            }
        }
        private void timerDeviceEvent_Tick(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem((obj) =>
            {
                //var task = Task.Factory.StartNew(() =>
                //     {
                GetDeviceEvent();
                //});
            });
            this.gridControl1.RefreshDataSource();
            this.pictureEdit1.Image = Session.EventImage;
        }
        public En_Result GetDeviceEvent()
        {
            try
            {
                //1.获取刷卡事件
                //4.多线程抓取视频并将照片放入到session中
                //2.多线程将数据写入到数据库
                //3.多线程根据卡号匹配用户信息 将结果放入到session中
                //界面定时刷新gridcontrol的数据源即可和图片数据源即可
                lock (Session.ListADSEventDataToDisplay)
                {
                    ADSHalDataStruct.ADS_Event[] acsevent = new ADSHalDataStruct.ADS_Event[100];
                    ADSHalDataStruct.ADS_CommunicationParameter com;
                    uint uRetCount = 0;
                    int iResult = -1;
                    var bal = new BAL.BAL_Records();
                    foreach (var device in Session._DicADsDevice.Values)
                    {
                        com = device.M_Comm;
                        for (int i = 0; i < 3; i++)
                        {
                            iResult = ADSHalAPI.ADS_ConnectController(ref Session._ADS_Comadapter, ref com);
                            if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                                break;
                        }
                        if (iResult != (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS)
                            continue;
                        List<En_ADSEventData> list = new List<Entitys.En_ADSEventData>();
                        iResult = ADSHalAPI.ADS_ReadEvents(ref Session._ADS_Comadapter, ref com, ref acsevent[0], 100, ref uRetCount);
                        if (iResult == (int)ADSHalConstant.ADS_ResultCode.ADS_RC_SUCCESS && uRetCount > 0)
                        {
                            #region 获取刷卡事件
                            for (int i = 0; i < uRetCount; i++)
                            {
                                var adsEvent = acsevent[i];
                                var enEvent = new En_ADSEventData();
                                enEvent.Event_ID = Guid.NewGuid().ToString();
                                var sub = device.ListSub.Where(kvSub => kvSub.Physics_ID == adsEvent.logicSubDeviceAddress.logicSubDevNumber).FirstOrDefault();
                                if (sub != null)
                                {
                                    enEvent.Event_LSubDeviceID = sub.LSubDevice_ID;
                                    enEvent.Event_SubDevice = sub.LSubDevice_Name;
                                    if (sub.IsUseNVR && sub.LonginUserID != -1)
                                    {
                                        #region 抓拍
                                        ThreadPool.QueueUserWorkItem((obj) =>
                                        {
                                            try
                                            {
                                                UInt32 lpSizeReturned = 0;

                                                byte[] byBuffer = new byte[Consts.CaptureImageBufferSize]; //最大处理768K大小
                                                IntPtr ipBuffer;
                                                ipBuffer = Marshal.UnsafeAddrOfPinnedArrayElement(byBuffer, 0);
                                                var isOK = HCNetSDK.NET_DVR_CaptureJPEGPicture_NEW(sub.LonginUserID, sub.NVRChannel, ref _NVR_JpgPara, ipBuffer, Consts.CaptureImageBufferSize, out lpSizeReturned);
                                                if (isOK == false)
                                                    return;
                                                byBuffer = new byte[lpSizeReturned];
                                                Marshal.Copy(ipBuffer, byBuffer, 0, Convert.ToInt32(lpSizeReturned));
                                                using (MemoryStream ms = new MemoryStream(byBuffer))
                                                {
                                                    Session.EventImage = Image.FromStream(ms);
                                                    ThreadPool.QueueUserWorkItem((temp) =>
                                                    {
                                                        try
                                                        {
                                                            var path = string.Format(@"{3}{0}年\{1}月\{2}日\",
                                                                                                             DateTime.Now.Year,
                                                                                                             DateTime.Now.Month,
                                                                                                             DateTime.Now.Day,
                                                                                                             Consts.StrEventPicPath
                                                                                                             );
                                                            if (!Directory.Exists(path))
                                                                Directory.CreateDirectory(path);
                                                            var fileName = string.Format("{0}{1}.jpg", path, DateTime.Now.ToString("yyyyMMddHHmmssfff"));
                                                            using (var fs = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite))
                                                            {
                                                                fs.Write(byBuffer, 0, byBuffer.Length);
                                                            }
                                                            new BAL.BAL_Records().UpdateEventRecordPic(enEvent.Event_ID, fileName);
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            var log = new Loger();
                                                            log.Log("保存抓拍图像错误,错误信息:");
                                                            log.LogException(ex);
                                                        }
                                                    });

                                                }
                                            }
                                            catch
                                            { }
                                        });
                                        #endregion
                                    }
                                }

                                var enCard = Session.ListEmployeeAndCard.Where(c =>
                                     c.Card_WignNo > 0
                                     && c.Card_WignNo == adsEvent.cardNumber.LoNumber
                                    ).FirstOrDefault();
                                if (enCard != null)
                                {
                                    enEvent.Emp_ID = enCard.Emp_ID;
                                    enEvent.EmplyeeName = enCard.Emp_Name;
                                    enEvent.Emp_NO = enCard.Emp_No;
                                    enEvent.Dept_ID = enCard.Dept_ID;
                                    enEvent.Event_Card = enCard.Card_No;
                                }
                                else
                                {
                                    enEvent.Emp_ID = string.Empty;
                                    enEvent.Event_Card = string.Format("非系统卡号:{0}", adsEvent.cardNumber.LoNumber);
                                }
                                enEvent.Event_Time = new DateTime(
                                   Convert.ToInt32(adsEvent.time.year) + 2000,
                                    Convert.ToInt32(adsEvent.time.month),
                                   Convert.ToInt32(adsEvent.time.day),
                                   Convert.ToInt32(adsEvent.time.hour),
                                   Convert.ToInt32(adsEvent.time.minute),
                                    Convert.ToInt32(adsEvent.time.sec)
                                    );
                                enEvent.Event_Name = ADSHelp.GetEventName((ADSHalConstant.ADS_EventType)adsEvent.type);

                                //enEvent.Event_Device = ADSHelp.Int2IP(com.deviceAddr).ToString();
                                enEvent.Event_Device = device.Device_Name;
                                //enEvent.Event_Card = adsEvent.cardNumber.LoNumber.ToString() + "-" + adsEvent.cardNumber.HiNumber.ToString();
                                enEvent.Event_EventValue = adsEvent.type;
                                //enEvent.Event_AttachValue
                                enEvent.Event_IsOpenDoor = enEvent.Event_Name.Contains('门') ? 1 : 0;
                                enEvent.Event_IsBrushCard = enEvent.Event_Name.Contains('卡') ? 1 : 0;
                                enEvent.Is_AlarmEvent = enEvent.Event_Name.Contains('警') ? 1 : 0;
                                enEvent.Event_DeviceID = device.Device_ID;


                                if (adsEvent.accessBlockedReason != 0)
                                {
                                    enEvent.ViollateCard_Reasion = ADSHalAPI.ADS_Helper_GetErrorMessage(adsEvent.accessBlockedReason);
                                }
                                list.Add(enEvent);
                                //多线程根据卡号匹配用户信息 将结果放入到session中
                                if (enEvent.Event_Name.Contains('卡') || enEvent.Event_Name.Contains('门'))
                                {
                                    var enToDisplay = new En_ADSEventDataToDisplay();
                                    if (enCard != null)
                                    {
                                        //enToDisplay.Emp_ID = enCard.Emp_ID;
                                        enToDisplay.Dept_Name = enCard.Dept_Name;
                                        enToDisplay.SiteName = enCard.SiteName;
                                        enToDisplay.WorkTypeName = enCard.WorkTypeName;
                                        enToDisplay.Job = enCard.Job;
                                        enToDisplay.Emp_Photo = enCard.Emp_Photo;
                                    }
                                    enToDisplay.EmplyeeName = enEvent.EmplyeeName;
                                    enToDisplay.Emp_NO = enEvent.Emp_NO;
                                    enToDisplay.Event_Card = enEvent.Event_Card;

                                    enToDisplay.Event_Time = new DateTime(
                                       Convert.ToInt32(adsEvent.time.year) + 2000,
                                        Convert.ToInt32(adsEvent.time.month),
                                       Convert.ToInt32(adsEvent.time.day),
                                       Convert.ToInt32(adsEvent.time.hour),
                                       Convert.ToInt32(adsEvent.time.minute),
                                        Convert.ToInt32(adsEvent.time.sec)
                                        );
                                    //enToDisplay.Device_Name = device.Device_Name;
                                    enToDisplay.Event_Name = ADSHelp.GetEventName((ADSHalConstant.ADS_EventType)adsEvent.type);

                                    enToDisplay.Event_Device = enEvent.Event_Device;
                                    enToDisplay.Event_SubDevice = adsEvent.logicSubDeviceAddress.logicSubDevNumber.ToString();

                                    enToDisplay.ViollateCard_Reasion = enEvent.ViollateCard_Reasion;

                                    if (Session.ListADSEventDataToDisplay.Count >= Consts.DeviceEventDataCount)
                                        Session.ListADSEventDataToDisplay.RemoveAt(0);
                                    Session.ListADSEventDataToDisplay.Add(enToDisplay);
                                }
                            #endregion
                            }
                            // 设置已经读取的事件数，防止重复读取
                            ADSHalAPI.ADS_IncreaseEventCount(ref Session._ADS_Comadapter, ref com, uRetCount);
                            //多线程将数据写入到数据库
                            ThreadPool.QueueUserWorkItem((obj) =>
                            {
                                try
                                {
                                    bal.InsertEventRecord(list);
                                }
                                catch (Exception ex)
                                {
                                    var log = new Loger();
                                    log.Log("将刷卡事件插入数据库出错,错误信息:");
                                    log.LogException(ex);
                                }
                            });
                        }
                    }
                }
                return En_Result.CreateSuccessResult();
            }
            catch (Exception ex)
            {
                var log = new Loger();
                log.Log("读取刷卡事件错误,错误信息:");
                log.LogException(ex);
                return En_Result.CreateFailedResult(ex.Message);
            }
        }

        #endregion
    }
}
